<template>
	<view>
		<uni-nav-bar  class="u-f-ajc" :statusBar="true" :fixed="true">
			 <view slot="left" @click="backAction()">
				 <uni-icons type="back" size="25" ></uni-icons>
			 </view>
			<view class="">
				<template>
					<view class="u-f-r u-f-ac u-f-ajc" style="width: 480rpx;" @click="showDeviceList">
						<view class="navTitle" >{{device.deviceName}}</view>
						<uni-icons v-if="type==2" :type="visible?'top':'bottom'" size="20"></uni-icons>
					</view>
					<view v-if="visible" class="selectDevice">
						<view class="selectItem u-f-ajc" :class="{'selected':item.isSelected}" v-for="(item,index) in deviceList" :key="index" @click="selectDevice(item)">{{item.deviceName}}</view>
					</view>
				</template>
				<!-- <template v-else>
					<view>消息列表</view>
				</template> -->
			</view>
		</uni-nav-bar>
		<view class="headerFixed">
			<view class="header">
				<image v-if="!currentVideo.url" :src="currentVideo.picUrl?currentVideo.picUrl:'https://statics.xmcsrv.net/weixin/noVideo.png'" class="img" :class="{'previewPic':currentVideo.picUrl}" mode="aspectFit"></image>
				<video v-if="currentVideo.url" id="video" style="width: 100%" :src="currentVideo.url" autoplay
					@ended="ended"></video>
			</view>
			<view class="u-f-sbc choose">
				<uni-datetime-picker type="daterange" :clear-icon="false" v-model="range" @change="change"
					@maskClick="maskClick">
					<view class="u-f-r u-f-ajc date">
						<view class="u-f-ajc calendar">
							<image src="https://statics.xmcsrv.net/weixin/calendar.png" mode=""></image>
							<text v-if="day">{{day}}天</text>
						</view>
					</view>
				</uni-datetime-picker>
				<view class="u-f-r" @click="showMsg">
					<view class="u-f-r msg" >
						<text class="all">{{msgType}}</text>
						<uni-icons v-if="isShowMsg" type="top" color="#3E3E3E" size="20" />
						<uni-icons v-else type="bottom" color="#3E3E3E" size="20" />
					</view>
				</view>
			</view>
		</view>
		<view v-if="list.length == 0" class="u-f-ajc u-f-c noData">
			<uni-icons custom-prefix="iconfont" type="icon-kong" size="64"></uni-icons>
			<view>暂无消息</view>
		</view>
		<view class="step">
			<view class="con" v-for="(item,index) in list" :key="index">
				<view class="itemList u-f-c">
					<view class="title">{{item.date}}</view>
					<view class="u-f-ac item" v-for="(item2,index2) in item.origin" :key="index2"
						>
						<view class="step-line step-line--before"  :style="{background:item2.selected?'#FF0025':'#D9D9D9'}"></view>
						<j-cell-slider v-if="item2.VideoInfo"  ref="jcell" :translate-x="100" :more="false" :action="false" style="width: 100%;padding: 10rpx 0 0 0;">
							<!-- <view  class="u-f-c">
								<text slot="title" class="time">{{item2.AlarmTime}}</text>
								<text slot="subTitle" class="type">{{item2.MsgType}}</text>
							</view> -->
							<view slot="title" class="time">{{item2.AlarmTime}}</view>
							<view slot="subTitle" class="type">{{item2.MsgType}}</view>
							<view slot="tips" class="" style="position: relative;" @click="itemClick(item2)">
								<image class="pic" :src="item2.alarmImageUrl" mode=""></image>
								<image v-if="item2.VideoInfo" class="play" src="https://statics.xmcsrv.net/weixin/play.png" mode=""></image>
							</view>
							<view slot="action" style="height: 100%">
								<view class="action" @tap="lookImage(item2)"> 查看图片 </view>
							</view>
						</j-cell-slider>
						<template v-else>
							<view class="u-f-c">
								<text class="time">{{item2.AlarmTime}}</text>
								<text class="type">{{item2.Msg}}{{item2.MsgType}}</text>
							</view>
							<view class="" style="position: relative;" @click="itemClick(item2)">
								<image class="pic" :src="item2.alarmImageUrl" mode=""></image>
								<image v-if="item2.VideoInfo" class="play" src="https://statics.xmcsrv.net/weixin/play.png" mode=""></image>
							</view>
						</template>
					</view>
				</view>
				<view class="step-container">
					<view class="step-line-item">
						<view class="step-line step-line--after"
							:class="[index==0?'step-line--after2':index==list.length-1?'step-line--after3':'step-line--after']">
						</view>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" :isMaskClick="false" type="bottom">
			<view>
				<j-cell-group>
					<view class="popup-content">
						<view class="u-f-c" style="background:#FFFFFF;padding:30rpx;">
							<view class="u-f-c" v-for="(item,index) in typeList" :key="index"
								@click="selectMsgType(item)">
								<view class="u-f-sbc msgType">
									<text>{{item.title}}</text>
									<uni-icons v-if="!item.selected" type="circle" color="#e5e5e5" size="30">
									</uni-icons>
									<uni-icons v-else type="checkbox" color="#FF0025" size="30"></uni-icons>
								</view>
								<view v-if="index!=typeList.length-1" class="b-line"></view>
							</view>
						</view>
					</view>
				</j-cell-group>
				<view style="padding:0 20rpx 20rpx">
					<button type="default" plain
						style="width: 100%;color: #FF0025 !important;border-color: #dcdcdc !important;background-color: #FFFFFF !important;"
						@click="closePopup">取消</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	const {
		getDiffDay
	} = require('@/utils/util.js');
	const {
		formatDate
	} = require('@/utils/util.js');
	import {AlarmMsg} from '@/utils/alarmMsg.js' 
	export default {
		data() {
			return {
				device: '',
				videoContext: null,
				currentVideo: {
					key: '',
					url: '',
					picUrl:''
				},
				range: '',
				day: 1,
				typeList: [{
						title: '全部消息',
						value: 'all',
						id: 0,
						selected: true
					},
					{
						title: '通知消息',
						value: 'DoorLockNotify',
						id: 1,
						selected: false
					},
					{
						title: '来电提醒',
						value: 'DoorLockCall',
						id: 2,
						selected: false
					},
					{
						title: '异常消息',
						value: 'DoorLockAlarm',
						id: 3,
						selected: false
					}
				],
				alarmJson:{
					'DoorLockNotify':'通知消息',
					'DoorLockCall':'来电提醒',
					'DoorLockAlarm':'异常消息',
					'VideoMotion':'移动侦测'
				},
				channelType: '所有通道',
				isShowMsg: false,
				msgType: '全部信息',
				active: -1,
				list: [],
				startTime: '',
				endTime: '',
				tempArr:[],
				deviceName:'',
				deviceList:[],
				visible:false,
				type:1,
			}
		},
		onLoad: function(options) {
			console.log('system===',uni.getSystemInfoSync());
			// console.log(JSON.parse(options.device));
			let currentDate = new Date().toJSON().split('T')[0]
			this.startTime = currentDate + ' ' +'00:00:00'
			this.endTime = currentDate + ' ' +'23:59:59'
			this.single = new Date().toJSON().split('T')[0]
			if(options.type==2){  // 首页跳转过来的
				this.type = options.type
				this.getDeviceListByPage()
			}else{
				let enData = decodeURIComponent(options.device)
				this.device = JSON.parse(enData);
				this.getMsgList()
			}
			console.log('dddddddd==type',this.type);
		},
		methods: {
			backAction(){
				uni.navigateBack({
					
				})
			},
			// 查询所有设备列表
			getDeviceListByPage() {
			    const data = {
			        // userGroupId: uni.getStorageSync('currentGroupId'),
			        // page: 1,
			        // limit: 999
			    };
			    getApp().globalData.api.getAllDeviceList(data, (result) => {
			        console.log('所有设备列表:', result);
					let sns = [];
					result.forEach((item)=>{
						if(!item.deviceNo.includes('vir')){
							this.deviceList.push(item)
							sns.push(item.deviceNo)
						}
					})
					if (sns.length > 0) {
					    this.getDeviceToken(sns);
					}
			    })
			},
			// 获取设备token
			getDeviceToken(sns) {
			    const data = {
			        sns: sns
			    };
			    getApp().globalData.api.getDeviceToken(data, (result) => {
			        console.log('获取设备token:', result);
			        this.deviceList.forEach((item) => {
						this.$set(item,'isSelected',false)
			            result.forEach((pro) => {
			                if (item.deviceNo === pro.sn) {
			                    item.token = pro.token;
			                }
			            });
			        });
			       this.deviceList[0].isSelected = true
			       this.device = this.deviceList[0]
				   this.getMsgList()
			        console.log('deviceList ===',this.deviceList);
			    });
			},
			showDeviceList(){
				if(this.deviceList.length>0){
					this.visible = !this.visible
				}
			},
			//选择设备
			selectDevice(item){
				this.device = item
				this.visible = false
				this.deviceList.forEach((item2)=>{
					if(item.deviceNo == item2.deviceNo){
						item2.isSelected = true
					}else{
						item2.isSelected = false
					}
				})
				this.getMsgList()
			},
			//查看图片
			lookImage(item){
				console.log('查看图片===',item);
				let pic = {
					alarmImageUrl:item.alarmImageUrl
				}
				uni.navigateTo({
					url:'./lookImage?alarmImageUrl='+encodeURIComponent(JSON.stringify(pic))
				})
				// uni.previewImage({
				// 	urls:[item.alarmImageUrl]
				// })
			},
			//获取消息列表
			getMsgList() {
				uni.showLoading({
					title: '正在获取'
				})
				let token = this.device.token
				let data = {
					sn: this.device.deviceNo,
					startTime: this.startTime,
					endTime: this.endTime,
					// AlarmEvent:
				}
				getApp().globalData.api.getLockAlarmMSgList(data, token, (result) => {
					uni.hideLoading()
					// this.list = result.AlarmArray
					this.sourceList = result.AlarmArray
					let tempList = result.AlarmArray
					let alarmIdArr = []
					let picInfoArr = []
					tempList.forEach((item,index) => {
						item.date = item.AlarmTime.split(' ')[0]
						item.AlarmEvent = item.AlarmEvent.split(':')[0]
						let msgType = JSON.parse(item.AlarmMsg)
						this.$set(item,'MsgType',AlarmMsg[msgType.MsgType])
						this.$set(item,'Msg',msgType.Msg?msgType.Msg:'')
						// 播放状态：播放1，暂停0，停止-1
						this.$set(item, 'status', -1)
						this.$set(item, 'key', index)
						if(item.PicInfo&&item.PicInfo.ObjName){
							alarmIdArr.push(item.AlarmId)
						}
						picInfoArr.push( {
							ObjName: (item.PicInfo&&item.PicInfo.ObjName)?item.PicInfo.ObjName:'',
							StorageBucket: (item.PicInfo&&item.PicInfo.StorageBucket)?item.PicInfo.StorageBucket:''
						})
						
						if(index==0){
							item.selected = true
						}else{
							item.selected = false
						}
					})
					if(result.AlarmArray.length>0&&result.AlarmArray[0].VideoInfo){
						let time = this.timeFormat(result.AlarmArray[0].AlarmTime)
						let data1 = {startTime:time[0],stopTime:time[1]}
						this.getVideoUrl(data1)
					}
					this.sourceList = tempList
					this.list = this.sortArray(tempList)
					
					if(alarmIdArr.length>0){
						this.getImgUrl(alarmIdArr,token)
						// this.getImgIcon(picInfoArr,token)
						this.timeFormat(result.AlarmArray[0].AlarmTime)
					}
				});
			},
			//获取报警图片
			getImgUrl(data,token){
				getApp().globalData.api.getPicUrl(data,token,(result)=>{
					let idArr = data
					idArr.forEach((item1,index1)=>{
						result.forEach((item2,index2)=>{
							if(index1==index2){
								this.$set(item2,'alarmId',item1)
							}
						})
					})
					console.log('报警图片===',result);
					this.sourceList.forEach((item,index)=>{
						result.forEach((urlItem)=>{
							if(item.AlarmId == urlItem.alarmId){
								this.$set(item,'alarmImageUrl',urlItem.url)
							}
						})
					})
					this.list = this.sortArray(this.sourceList)
					this.currentVideo.picUrl = this.list[0].origin[0].alarmImageUrl?this.list[0].origin[0].alarmImageUrl:''
				});
			},
			//获取缩略图
			getImgIcon(data,token){
				getApp().globalData.api.getCloudVideoIcon(data,token,(result)=>{
					console.log('缩略图图片',result);
					this.sourceList = this.sourceList.map((item,index)=>{
						return{...item,alarmImageUrl:result[index].url}
					})
					this.list = this.sortArray(this.sourceList)
					this.currentVideo.picUrl = this.list[0].origin[0].alarmImageUrl?this.list[0].origin[0].alarmImageUrl:''
				});
			},
			//获取报警视频
			getVideoUrl(data,item){
				let token = this.device.token
				getApp().globalData.api.getVideoUrl(data,token,(result)=>{
					console.log('报警视频',result);
					this.currentVideo.url = result.url
					this.currentVideo.picUrl = item?item.alarmImageUrl:''
				});
			},
			//时间转化
			timeFormat(date){
				let time = new Date(date)
				let transferTime1 = time.getTime() -10*1000
				let transferTime2 = time.getTime() + 10*1000
				let  newDate = formatDate(new Date(transferTime1))
				return [formatDate(new Date(transferTime1)),formatDate(new Date(transferTime2))]
			},
			//选中某条播放视频
			itemClick(item) {
				if(!item.selected){
					this.list.forEach((item2)=>{
						item2.origin.forEach((item3,index)=>{
							if(item.AlarmId == item3.AlarmId){
								item3.selected = true
							}else{
								item3.selected = false
							}
						})
					})
					this.list=this.list.map((item2)=>{
						item2.origin.map((item3,index)=>{
							if(item.AlarmId == item3.AlarmId){
								item3.selected = true
							}else{
								item3.selected = false
							}
						})
						return {...item2}
					})
					console.log(this.list);
					let time = this.timeFormat(item.AlarmTime)
					let data ={startTime:time[0],stopTime:time[1]} 
					if(item.VideoInfo){
						this.getVideoUrl(data,item)
					}else if(item.PicInfo){
						this.currentVideo.picUrl = item.alarmImageUrl?item.alarmImageUrl:''
						this.currentVideo.url = ''
					}
				}else{
					if(item.VideoInfo){
						uni.showToast({
							title:'正在播放该视频'
						})
					}else if(item.PicInfo){
						this.currentVideo.picUrl = item.alarmImageUrl?item.alarmImageUrl:''
						this.currentVideo.url = ''
					}
					
				}
			},
			//日期选择
			change(ev) {
				console.log('change事件:', ev);
				this.range = ev
				this.day = getDiffDay(this.range[0], this.range[1]) + 1
				console.log(typeof this.day);
				this.startTime = this.range[0] + ' ' + '00:00:00'
				this.endTime = this.range[1] + ' ' + '23:59:59'
				this.getMsgList()
			},
			maskClick(ev) {
				console.log('maskClick事件:', ev);
			},
			//显示消息弹框
			showMsg() {
				this.isShowMsg = true
				this.$refs.popup.open('bottom')
			},
			//选择消息类型
			selectMsgType(item) {
				this.typeList.forEach((item2) => {
					if (item2.id == item.id) {
						item2.selected = !item2.selected
					} else {
						item2.selected = false
					}
				})
				this.msgType = item.title
				let arr = []
				if(item.value=='all'){
					arr = this.sourceList
				}else{
					arr = this.fuzzyQuery(this.sourceList,item.value)
				}
				arr.forEach((item,index)=>{
					if(index==0){
						item.selected = true
					}else{
						item.selected = false
					}
				})
				this.list = this.sortArray(arr)
				if(arr.length>0){
					this.currentVideo.picUrl = this.list[0].origin[0].alarmImageUrl?this.list[0].origin[0].alarmImageUrl:''
					if(this.list[0].origin[0].VideoInfo){
						let time = this.timeFormat(this.list[0].origin[0].AlarmTime)
						let data ={startTime:time[0],stopTime:time[1]} 
						this.getVideoUrl(data)
					}
				}else{
					this.currentVideo.picUrl = ''
					this.currentVideo.url = ''
				}
				console.log('选择',this.list);
				this.closePopup()
			},
			// 按日期分类
			sortArray(beforeData) {
				let tempArr = [];
				var afterData = [];
				for (let i = 0; i < beforeData.length; i++) {
					beforeData[i].date = beforeData[i].date
					if (tempArr.indexOf(beforeData[i].date) === -1) {
						afterData.push({
							date: beforeData[i].date,
							origin: [beforeData[i]]
						});
						tempArr.push(beforeData[i].date);
					} else {
						for (let j = 0; j < afterData.length; j++) {
							if (afterData[j].date == beforeData[i].date) {
								afterData[j].origin.push(beforeData[i]);
								break;
							}
						}
					}
				}
				console.log(afterData, 'afterData');
				return afterData
			},
			// 搜索查询
			fuzzyQuery(list, keyword) {
			   var reg = new RegExp (keyword);
			   var arr = [];
			   for (var i = 0; i< list.length; i++) {
			      if (reg.test (list[i].AlarmEvent)) {
				   arr.push(list[i]);
			      }
			    }
			    return arr;
			},
			// 关闭弹框
			closePopup() {
				this.isShowMsg = false
				this.$refs.popup.close()
			},
			//播放结束
			ended(ev) {
				console.log('播放结束：', ev, this.currentVideo);
				// if (this.onStop) {
				// 	this.closeLivestream()
				// 	this.videoContext = null
				// }
			},
			// 停止设备码流
			closeLivestream(callback) {
				const token = this.device.token;
				const data = {
					channel: '0',
					stream: '0'
				};
				getApp().globalData.api.closeLivestream(data, token, (result) => {
					console.log('停止设备码流:', result);
				});
			},
			
			
		}
	}
</script>

<style lang="less" scoped>
	// /deep/.uni-calendar__header-text{
	// 	color: #007aff;
	// }
	/deep/.uni-navbar__header-container{
		align-items: center;
	}
	.navTitle{
		
	}
	.selectDevice{
		position: absolute;
		background: white;
		top:44px;
		// left: 0rpx;
		// right: 0rpx;
		width: 480rpx;
		max-height: 480rpx;
		// height: 480rpx;
		z-index: 999;
		border-radius: 10rpx;
		padding: 15rpx;
		overflow: scroll;
		.selectItem{
			border-bottom: 1px solid #f1f1f1;
			padding-bottom: 10rpx;
			height: 50rpx;
			color: #333;
		}
		.selected{
			color: #FF0025;
		}
	}
	.headerFixed{
		position: fixed;
		left: 0;
		right: 0;
		top: 44px;
		z-index: 99;
	}
	.header {
		width: 100vw;
		min-height: 526rpx;
		background: #000000;
		display: flex;
		justify-content: center;
		align-items: center;
		.img{
			width: 120rpx;
			height: 120rpx;
		}
		.previewPic{
			width: 100vw;
			height: 526rpx;
		}
	}

	.choose {
		// margin: 40rpx;
		padding: 40rpx;
		position: relative;
		background: #f5f7fb;

		.date {
			width: 200rpx;
			height: 60rpx;
			// border: 1rpx solid #A4A4A5;
			border-radius: 12rpx;
			background: #C8C8C8;

			.icon {
				width: 40rpx;

				image {
					width: 30rpx;
					height: 30rpx;
				}
			}

			.calendar {
				height: 58rpx;
				// border-left: 1rpx solid #A4A4A5;
				// border-right: 1rpx solid #A4A4A5;
				width: 120rpx;
				color: white;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}
			}
		}

		.msg {
			margin-left: 30rpx;

			text {
				margin-right: 10rpx;
				color: #5A5A5A;
				font-size: 26rpx;
			}
		}

		.chooseMsgType {
			position: absolute;
			left: -40rpx;
			right: -40rpx;
			top: 60rpx;
			background: white;
			z-index: 99;
			padding: 30rpx;

			.msgType {
				height: 60rpx;
				color: #000;
				opacity: 0.8;
			}

			.b-line {
				height: 1rpx;
				background: #e5e5e5;
				margin: 20rpx 0;

			}
		}
	}
	.noData{
		margin-top: 680rpx;
	}

	.step {
		margin:650rpx 30rpx 30rpx 30rpx;

		.con {
			flex-direction: row-reverse;
			display: flex;
		}

		.itemList {
			// padding: 40rpx;
			width: 100%;
			margin-right: 60rpx;

			.title {
				background: #FF0025;
				width: 205rpx;
				height: 58rpx;
				border-radius: 12rpx;
				color: white;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: -50rpx;
				margin-top: 20rpx;
				z-index: 10;
				font-size: 26rpx;
			}
			.action{
				background: #FF0025;
				height: 100%; 
				display: flex; 
				justify-content: center; 
				align-items: center; 
				padding: 0 20rpx; 
				font-size: 26rpx
			}
			.item {
				background: white;
				display: flex;
				justify-content: space-between;
				padding:0 30rpx;
				border-bottom: 1px solid #E8E8E8;
				margin-top: 20rpx;
				border-radius: 15rpx;
				width: 100%;

				.msg {
					color: #000000;
					font-weight: bold;
					font-size: 30rpx;
				}

				.all {
					color: #989898;
					font-size: 26rpx;
				}

				.pic {
					width: 202rpx;
					height: 114rpx;
				}

				.play {
					position: absolute;
					width: 40rpx;
					height: 40rpx;
					right: 80rpx;
					top: 33rpx;
				}

				.time {
					color: #5A5A5A;
					font-size: 26rpx;
				}

				.type {
					color: #FF0025;
					font-size: 26rpx;

				}
			}
		}

		.line {
			background: #939393;
			width: 10px;
			position: relative;
			// height: 40rpx;
			margin-left: -40rpx;
		}

		.step-container {
			/* #ifndef APP-NVUE */
			display: inline-flex;
			/* #endif */
			width: 30px;
			flex-direction: column;
		}

		.step-line-item {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: column;
			flex: 1;
			align-items: center;
			justify-content: center;
		}

		.step-line {
			width: 1px;
			background: #D9D9D9;
		}

		.step-line--after {
			flex: 1;
			transform: translate(0px, 1px);
		}

		.step-line--after2 {
			transform: translate(0px, 40px);
		}

		.step-line--after3 {
			transform: translate(0px, -45px);
		}

		.step-line--before {
			height: 20rpx;
			width: 20rpx;
			background: #FF0025;
			border-radius: 10rpx;
			position: absolute;
			left: 45rpx;
			z-index: 10;
			// top: 20rpx;
			// transform: translate(0px, 100px);
		}

		.step-circle {
			width: 10px;
			height: 10px;
			border-radius: 50%;
			background: #FF0025;
			margin: 4px 0px 5px 0px;
		}

		.step-check {
			height: 14px;
			line-height: 14px;
			margin: 2px 0px;
		}

	}

	.popup-content {
		.msgType {
			height: 60rpx;
			color: #666;
		}

		.b-line {
			height: 1rpx;
			background: #e5e5e5;
			margin: 20rpx 0;

		}
	}

	.video-list {
		width: 100vw;
		height: 40vw;
		white-space: nowrap;
	}

	.video {
		display: inline-block;
		width: 30vw;
		height: 30vw;
		overflow: hidden;
		border: 1px solid #999999;
		margin: 20rpx;
	}

	.video-control {
		position: relative;
		display: flex;
		width: 100%;
		height: 100%;
		justify-content: center;
		align-items: center;
	}

	.video-nothing {
		display: flex;
		width: 100%;
		height: 100%;
		justify-content: center;
		align-items: center;
	}
</style>
